package com.aiti.myproject.client;

import com.aiti.myproject.client.service.LoginService;
import com.aiti.myproject.client.service.LoginServiceAsync;
import com.aiti.myproject.client.widgets.PhotoGallery;
import com.aiti.myproject.client.widgets.UploadPhoto;
import com.aiti.myproject.shared.LoginInfo;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Project_II___Web implements EntryPoint {

	private LoginInfo loginInfo = null;
	private VerticalPanel loginPanel;
	private UploadPhoto uploadPhoto;
	private PhotoGallery photoGallery;
	private Label loginLabel, uploadLabel;
	private Anchor signInLink, signOutLink;
	private LoginServiceAsync loginServiceAsync;

	@Override
	public void onModuleLoad() {
		photoGallery = new PhotoGallery(this);
		loginPanel = new VerticalPanel();
		loginLabel = new Label(
				"Please sign in to your Google Account to access the Photo Editor web application !");
		uploadLabel = new Label("Please select a file to upload: ");
		signInLink = new Anchor("Sign in");
		signOutLink = new Anchor("Sign out");
		loginServiceAsync = GWT.create(LoginService.class);
		loginServiceAsync.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {

					@Override
					public void onSuccess(LoginInfo result) {
						loginInfo = result;
						if (loginInfo.isLoggedIn()) {
							uploadPhoto = new UploadPhoto(loginInfo);
							uploadPhoto.addGalleryUpdatedEventHandler(photoGallery);
							RootPanel.get("imageGallery").add(photoGallery);
							loadProject();
						} else {
							loadLogin();
						}
					}

					@Override
					public void onFailure(Throwable caught) {

					}
				});
	}

	private void loadLogin() {
		signInLink.setHref(loginInfo.getLoginUrl());
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		RootPanel.get("login").add(loginPanel);
	}

	private void loadProject() {
		VerticalPanel verticalPanel = new VerticalPanel();
		signOutLink.setHref(loginInfo.getLogoutUrl());
		verticalPanel.add(signOutLink);
		verticalPanel.add(uploadLabel);
		verticalPanel.add(uploadPhoto);
		RootPanel.get("login").add(verticalPanel);
	}
	
	public LoginInfo getLoginInfo() {
		return loginInfo;
	}
}
